package com.zhoutao.blog.seven.service.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.zhoutao.blog.seven.dao.repository.MenuRepository;
import com.zhoutao.blog.seven.model.converter.MenuConverter;
import com.zhoutao.blog.seven.model.response.Menu;
import com.zhoutao.blog.seven.service.MenuService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MenuServiceImpl implements MenuService {


    private final static Cache<String, List<Menu>> MENU_CACHE =
            CacheBuilder.newBuilder().maximumSize(1).expireAfterWrite(30, TimeUnit.DAYS).build();
    public final MenuConverter menuConverter;
    private final MenuRepository menuRepository;

    public MenuServiceImpl(MenuRepository menuRepository, MenuConverter menuConverter) {
        this.menuRepository = menuRepository;
        this.menuConverter = menuConverter;
    }

    @Override
    public void cleanCache() {
        MENU_CACHE.invalidateAll();
    }

    @Override
    @SneakyThrows
    public List<Menu> all() {
        return MENU_CACHE.get("MENU", () -> {
            log.info("主页菜单缓存已失效,开始从数据库中查询菜单");
            return menuRepository.all().stream().map(menuConverter::converterFrom).collect(Collectors.toList());
        });
    }
}
